package com.ang.interceptor;

/**
 * @author ssang
 * @date 2022-09-27 15:19
 */
import com.ang.annotation.SensitiveField;
import com.ang.utils.Base64Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import org.apache.ibatis.executor.Executor;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 查询拦截器
 * 对QueryWrapper的入参无效
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class})
})
public class QueryInterceptor implements Interceptor {
    /**
     * 使用 @Param("crypt")注解的参数（只支持自定义对象 且同时添加CryptEntity和CryptField注解）
     */
    public static final String paramVal = "crypt";
    public static final String ewVal = "ew";

    @Resource
    private CommonUtil commonUtil;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //获取查询参数，查询条件是否需要加密
        Object[] args = invocation.getArgs();
        Object parameter = args[1];
        Object result = null;
        //设置执行标识
        boolean flag = true;
        if (parameter instanceof Map) {
            Map paramMap = (Map) parameter;
            if (paramMap.containsKey(paramVal)) {
                //包含@Param("crypt")注解的参数
                Object queryParameter = paramMap.get(paramVal);
                if (commonUtil.needToCrypt(queryParameter)) {
                    //执行sql，还原加密后的报文
                    MappedStatement mappedStatement = (MappedStatement) args[0];
                    result = commonUtil.proceed(invocation, mappedStatement, queryParameter);
                    flag = false;
                }
            }else if(paramMap.containsKey(ewVal)){
                //包含queryWrapper的参数，且封装的为对象
                QueryWrapper queryWrapper = (QueryWrapper) paramMap.get(ewVal);
                Object queryParameter = queryWrapper.getEntity();
                if (commonUtil.needToCrypt(queryParameter)) {
                    //执行sql，还原加密后的报文
                    MappedStatement mappedStatement = (MappedStatement) args[0];
                    result = commonUtil.proceed(invocation, mappedStatement, queryParameter);
                    flag = false;
                }
            }
        }
        //传参为BO，DTO，Model
        else if (commonUtil.needToCrypt(parameter)) {
            //执行sql，还原加解密后的报文
            MappedStatement mappedStatement = (MappedStatement) args[0];
            result = commonUtil.proceed(invocation, mappedStatement, parameter);
            flag = false;
        }


        //是否需要执行
        if (flag) {
            result = invocation.proceed();
        }
        if (Objects.isNull(result)) {
            return null;
        }
        // 返回列表数据，循环检查
        if (result instanceof ArrayList) {
            ArrayList resultList = (ArrayList) result;
            if (CollectionUtils.isNotEmpty(resultList) && commonUtil.needToCrypt(resultList.get(0))) {
                for (Object resultObject : resultList) {
                    decrypt(resultObject);
                }
            }
        } else if (commonUtil.needToCrypt(result)) {
            decrypt(result);
        }
        //返回结果
        return result;
    }

    /**
     * @param resultObject 需要解密的对象
     * @return
     * @throws Exception
     */
    private Object decrypt(Object resultObject) throws Exception {
        // 取出resultType的类
        Class<?> resultCls = resultObject.getClass();
        Field[] fields = resultCls.getDeclaredFields();
        for (Field field : fields) {
            // 获取所有被Sensitive注解的字段
            SensitiveField cryptAnnotation = field.getAnnotation(SensitiveField.class);
            if (cryptAnnotation != null) {
                field.setAccessible(true);
                Object obj = field.get(resultObject);
                if (obj instanceof String) {
                    String val = obj.toString();
                    field.set(resultObject, Base64Util.decrypt(val));
                }
            }
        }
        return resultObject;
    }
}
